#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.views import View

from app01.models import *


def auther_list(request):
    authers = Auther.objects.all()
    return render(request, "bookmanage/auther/auther_list.html",
                  {"auther_list": authers})


def auther_delete(request, id):
    get_book_id = Auther.objects.filter(pk=id)
    if get_book_id.first():
        get_au_detail = get_book_id.first().autherdetail
        if get_au_detail:
            get_au_detail.delete()
        get_book_id.delete()
    return redirect(reverse("auther_list"))


class Authadd(View):
    def get(self, request):
        return render(request, "bookmanage/auther/auther_add.html")

    def post(self, request):
        name = request.POST.get("name")
        address = request.POST.get("address")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        # 忽略错误，直接返回
        try:
            detail = Autherdetail.objects.create(email=email, phone=phone)
            Auther.objects.create(name=name, address=address, autherdetail_id=detail.id)
        except:
            pass
        return redirect(reverse("auther_list"))


class Authchange(View):
    def get(self, request, id):
        get_aid = Auther.objects.filter(pk=id)
        if get_aid:
            return render(request, "bookmanage/auther/auther_change.html",
                          {"auther": get_aid.first()})
        return redirect(reverse("auther_list"))

    def post(self, request, id):
        get_aid = Auther.objects.filter(pk=id)
        if get_aid:
            name = request.POST.get("name")
            address = request.POST.get("address")
            email = request.POST.get("email")
            phone = request.POST.get("phone")

            get_aid = get_aid.first()
            Autherdetail.objects.filter(pk=get_aid.autherdetail.id).update(email=email, phone=phone)
            get_aid.name = name
            get_aid.address = address
            get_aid.save()

            return redirect(reverse("auther_list"))
